/* eslint-disable */
import { mixin } from "../../util/misc";
import Modal from "./modal.vue";

// Vue, 实例， 等初始化后，在赋值
let ModalConstructor, Vue;

// 当前实例化的弹窗
let dialogs = [];

// 销毁一个实例
function dialogRemove(dialog) {
  if (dialog.__modal__destroy__) {
    return;
  }
  // 防止多次调用销毁
  dialog.__modal__destroy__ = true;
  let el = dialog.$el;
  try {
    el.parentNode.removeChild(el);
  } catch (e) {}

  // 销毁实例
  dialog.$destroy();
}

// 关闭时 触发的事件
function onClose(index) {
  let buttons = this.buttons;
  let i = index - 1;
  let callback = (buttons[i] && buttons[i].callback) || this.callback;
  let flag = (callback && callback.call(this, index) === false) || false;

  if ((this.canClose = !flag)) {
    let n = dialogs.indexOf(this);
    if (n > -1) {
      dialogs.splice(n, 1);
    }

    dialogRemove(this);
  }
}

// 用户初始化 alert 、 confirm 等预设值的 弹窗
function init(defOption = {}) {
  return function(options = {}) {
    if (typeof options === "string") {
      options = { message: options };
    }

    // 新建一个实例
    let dialog = new ModalConstructor({
      el: document.createElement("div")
    });
    dialogs.push([dialog, this]);
    let resolveFn;
    dialog.$on("close", function(index) {
      onClose.call(this, index);
      if (this.canClose && resolveFn) {
        // 关闭的时候 触发
        resolveFn(index);
      }
    });
    // 将相关的参数 设置到 实例 dialog 上面
    mixin(dialog, defOption, options);

    // 加入文档流
    document.body.appendChild(dialog.$el);
    Vue.nextTick(function() {
      dialog.visable = true;
    });
    dialog.then = function() {
      return new Promise(function(resolve) {
        resolveFn = resolve;
      });
    };
    return dialog;
  };
}

// alert 预设值为 一个按钮
export let alert = init({
  buttons: [
    {
      text: "确定",
      isLight: true
    }
  ]
});

// confirm 预设值为 两个按钮
export let confirm = init({
  maskHide: false,
  buttons: [
    {
      text: "取消"
    },
    {
      text: "确定",
      isLight: true
    }
  ]
});

// message 无预设值
export let message = init();

// 这个是用来注册 插件用的 install
export default function install(
  vue,
  { alertName, confirmName, messageName } = {}
) {
  if (Vue) {
    return;
  }
  Vue = vue;
  ModalConstructor = vue.extend(Modal);
  Vue.prototype["$" + alertName] = alert;
  Vue.prototype["$" + confirmName] = confirm;
  Vue.prototype["$" + messageName] = message;

  // destroyed 销毁弹窗实例
  Vue.mixin({
    destroyed() {
      let dls = [];
      dialogs.forEach(item => {
        let [dl, owner] = item;
        if (owner == this) {
          dialogRemove(dl);
        } else {
          dls.push(item);
        }
      });
      dialogs = dls;
    }
  });
}
